package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

//Chart 客户会话
type Chart struct {
	Id uint `json:"id" orm:"pk;auto"`
	Uid uint //用户id
	MerchantId uint //商家id,暂时可不用
	ManagerUid uint //客服id
	UnReadCnt uint //未读数量
	CreatedAt time.Time
	UpdatedAt time.Time
	Status uint
}

func init()  {
	orm.RegisterModel(new(Chart))
}

//ChartCreate 根据顾客id创建会话，存在则直接返回
func ChartCreate(uid uint) (chart Chart, err error) {
	//查询用户是否存在
	u := UserGet(uid)
	if u.Id == 0 {
		return chart, fmt.Errorf("用户不存在")
	}
	if u.Types == 2 {
		return chart, fmt.Errorf("只有顾客可以开启会话")
	}
	//查询会话
	o := orm.NewOrm()
	err = o.QueryTable(Chart{}).Filter("uid", uid).One(&chart)
	if err != nil && err != orm.ErrNoRows {
		panic(err)
	}

	//存在则直接返回
	if chart.Id != 0 {
		if chart.Status == 0 {
			chart.Status = 1
			_, err = o.Update(&chart)
			if err != nil {
				panic(err)
			}
		}
		return chart, nil
	}

	//不存在则新增
	chart.Uid = uid
	chart.CreatedAt = time.Now()
	chart.UpdatedAt = time.Now()
	chart.Status = 1
	i, err := o.Insert(&chart)
	if err != nil {
		panic(err)
	}
	chart.Id = uint(i)
	return chart, nil
}

func ChartGet(chartId uint) (chart Chart) {
	o := orm.NewOrm()

	o.QueryTable(Chart{}).Filter("id", chartId).One(&chart)
	return
}

//ChartUnReadAdd 增加会话未读数量
func ChartUnReadAdd(chartId uint) uint {
	chart := ChartGet(chartId)
	if chart.Id == 0 {
		return 0
	}
	if chart.Status == 0 {
		chart.UnReadCnt = 1
	} else {
		chart.UnReadCnt ++
	}
	chart.Status = 1

	o := orm.NewOrm()
	_, err := o.Update(&chart)
	if err != nil {
		panic(err)
	}
	return chart.UnReadCnt
}

func (this *Chart) Save() {
	o := orm.NewOrm()
	if this.Id == 0 {
		i, err := o.Insert(this)
		if err != nil {
			panic(err)
		}
		this.Id = uint(i)
	} else {
		_, err := o.Update(this)
		if err != nil {
			panic(err)
		}
	}
}

//消息已读
func ChartReaded(uid uint) {
	o := orm.NewOrm()

	chart := Chart{}
	o.QueryTable(Chart{}).Filter("uid", uid).One(&chart)
	if chart.Id == 0 || chart.UnReadCnt == 0 {
		return
	}

	chart.UnReadCnt = 0
	o.Update(&chart)
}

func ChartGetByUid(uid uint) (chart Chart) {
	o := orm.NewOrm()

	o.QueryTable(Chart{}).Filter("uid", uid).One(&chart)

	return
}